'use client';

import type { TMetadata } from '@/types';
import { useQuery } from '@tanstack/react-query';
import {
  clientQueryAllMenu,
  queryPostTemplateStatistics,
} from '@/services/api';
import type { IMenu, IPostTemplateStatistics } from '@/interfaces';
import NavbarAdminPage from '@/app/[locale]/admin/navbar';
import Alert from '@/app/[locale]/alert/alert';
import { NavbarPage } from '@/app/[locale]/navbar';
import FooterPage from '@/app/[locale]/footer';
import AlertLoad from '@/app/[locale]/alert/load';
import { PostTemplateAdminContext } from '@/contexts/admin/forum/postTemplate';
import ListPostTemplateAdminPage from '@/app/[locale]/admin/forum/postTemplate/list';

export default function PostTemplateAdminPage({
  metadata,
}: {
  metadata: TMetadata;
}) {
  return (
    <>
      <NavbarPage metadata={metadata} />
      <PostTemplateAdmin metadata={metadata} />
      <FooterPage metadata={metadata} />
    </>
  );
}

const PostTemplateAdmin = ({ metadata }: { metadata: TMetadata }) => {
  const clientQueryMenusQuery = useQuery(
    metadata.all['menus'].k,
    async (context) => {
      return (await clientQueryAllMenu()) as IMenu[];
    },
    {
      initialData: metadata.all['menus'].v as IMenu[],
    },
  );

  const queryPostTemplateStatisticsQuery = useQuery(
    ['/forum', '/tags', '/statistics'],
    async () => {
      return (await queryPostTemplateStatistics()) as IPostTemplateStatistics;
    },
  );

  if (clientQueryMenusQuery.data) {
    const menus = clientQueryMenusQuery.data;

    return (
      <PostTemplateAdminContext.Provider value={{ metadata }}>
        <div className="container-fluid">
          <div className="vstack gap-4">
            <NavbarAdminPage menus={menus} />

            <div className="row">
              <div className="col">
                <div className="card">
                  <div className="card-body">
                    <h6 className="card-subtitle mb-2 text-muted">
                      帖子模板总数
                    </h6>
                    <h5 className="card-title">
                      {queryPostTemplateStatisticsQuery.data?.count || 0}
                    </h5>
                  </div>
                </div>
              </div>
            </div>

            <ListPostTemplateAdminPage />

            <div></div>
          </div>
        </div>
      </PostTemplateAdminContext.Provider>
    );
  }

  if (clientQueryMenusQuery.error) {
    return <Alert message={clientQueryMenusQuery.error} type="error" />;
  }

  return <AlertLoad />;
};
